package com.dong.trues;


public class Demo2 {
    private volatile int flag;
    public static void main(String[] args) {
        Demo2 demo2 = new Demo2();
        new Thread(()->demo2.test1(5)).start();
        new Thread(()->demo2.test2(5)).start();
        new Thread(()->demo2.test3(5)).start();
    }
    public synchronized void test1(int n) {
        try {
            for (int i = 1; i <= n; i++) {
                while (flag != 0) {
                    wait();
                }
                System.out.print("A");
                flag = 1;
                this.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void test2(int n) {
        try {
            for (int i = 1; i <= n; i++) {
                while (flag != 1) {
                    wait();
                }
                System.out.print("B");
                flag = 2;
                this.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void test3(int n) {
        try {
            for (int i = 1; i <= n; i++) {
                while (flag != 2) {
                    wait();
                }
                System.out.println("C");
                flag = 0;
                this.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
